import http from 'http';
import path from 'path';

import cors from '@koa/cors';
import Koa from 'koa';
import { koaBody } from 'koa-body';
import staticFolder from 'koa-static';

import { SERVER } from '../core/loadConfig.ts';
import { errorHandler } from '../core/middlewares/errorHandler.ts';
import { responseHandler } from '../core/middlewares/responseHandler.ts';
import { RouterPlus } from '../core/router.ts';
import { wssInit } from '../core/service/webSocket.ts';

export const app = new Koa();
export const initApp = () => {
  const server = http.createServer(app.callback());

  // 配置跨域
  app.use(
    cors({
      origin: '*', //允许所有域名访问
      exposeHeaders: ['WWW-Authenticate', 'Server-Authorization'],
      maxAge: 5,
      credentials: true, //允许携带cookie
      allowMethods: ['GET'], //允许的请求方法
      allowHeaders: ['Content-Type', 'Authorization', 'Accept'], //允许的请求头
    }),
  );

  // 是否启用 WebSocket
  if (SERVER.WS.ENABLE) {
    wssInit(server);
  }

  app.use(errorHandler);
  // 配置静态文件目录
  app.use(staticFolder(path.join('/public')));

  // 配置请求体解析，默认关闭 multipart 避免和 multer 冲突
  app.use(koaBody());

  // app.use(loggerMiddleware);

  RouterPlus.init(app).then(() => {
    console.log('controllers loaded');
    app.use(responseHandler);
  });
};
